//
//  CarcircleCell.m
//  CarUser
//
//  Created by 王森林 on 2019/1/19.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "CarcircleCell.h"
#import "UserRes.h"
#import "SDPhotoBrowser.h"
//#import "YCPhotoBrowserController.h"
//#import "YCPhotoBrowserAnimator.h"
@interface CarcircleCell()<SDPhotoBrowserDelegate>

@property (nonatomic, strong) UIImageView *logoImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *dateLabel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UIView *imgsView;
@property (nonatomic, strong) UIButton *zanBtn;
@property (nonatomic, strong) UIButton *commentBtn;
@property (nonatomic, strong) UILabel *lineLabel;
@property (nonatomic, strong) NSDictionary *dict;
@property (nonatomic, strong) NSMutableArray *photos;
@property (nonatomic, assign) NSInteger isZan;
@end

#define BTNTAG 1000000
@implementation CarcircleCell


- (void)setData:(id)data
{
    
    if (data) {
        self.dict = [NSDictionary dictionaryWithDictionary:data];
        [self createUIWithData];
    }
 
}

- (void)createUIWithData
{
      self.photos = [NSMutableArray new];
      [self.contentView addSubview:self.logoImageView];
      [self.contentView addSubview:self.nameLabel];
      [self.contentView addSubview:self.dateLabel];
      [self.contentView addSubview:self.titleLabel];
      [self.contentView addSubview:self.contentLabel];
      [self.contentView addSubview:self.imgsView];
      [self.contentView addSubview:self.zanBtn];
      [self.contentView addSubview:self.commentBtn];
      [self.contentView addSubview:self.lineLabel];
    
    
//    self.logoImageView.image = IMG(@"car_test2");
    [self.logoImageView sd_setImageWithURL:[NSURL URLWithString:APPEND_URL(BASE_URL, [self.dict objectForKey:@"headIcon"])] placeholderImage:IMG(@"headImage")];
    self.nameLabel.text = [self.dict objectForKey:@"nickName"];
    self.dateLabel.text = [self.dict objectForKey:@"SJ0000"];
    self.titleLabel.text = [self.dict objectForKey:@"BT0000"];
//    self.contentLabel.text = [self.dict objectForKey:@"WZNR00"];
    NSString * htmlString = [self.dict objectForKey:@"WZNR00"];
//    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil  error:nil];
    
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [attrStr addAttribute:NSForegroundColorAttributeName value:Common_TextLowColor range:NSMakeRange(0, attrStr.length)];
    
    self.contentLabel.attributedText = attrStr;
   
    [self.zanBtn setTitle:[NSString stringWithFormat:@"%@",[self.dict objectForKey:@"DZS000"]] forState:UIControlStateNormal];
    [self.commentBtn setTitle:[NSString stringWithFormat:@"%@",[self.dict objectForKey:@"PLS000"]] forState:UIControlStateNormal];
    
    
    [self createConstraint];
    NSArray *ary = [self.dict objectForKey:@"imageList"];
    
//    dispatch_async(dispatch_get_main_queue(), ^{
//
////        [SVProgressHUD showInfoWithStatus:@"付款成功"];
////
////        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_PaySuccess object:nil];
////
////        //                    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
////        //
////        //                    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
////        //                        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_PaySuccess object:nil];
////        //                    });
////
////
////        //                [SVProgressHUD dismissWithDelay:10];
//    });
    
    
    if (ary.count > 0) {
        [self createImgsWithAry:[self.dict objectForKey:@"imageList"]];
    } else {
        [self.imgsView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo (0);
            make.bottom.equalTo(self.contentView).offset(-60);
        }];
        
    }
    
    
   self.isZan = [[self.dict objectForKey:@"DZFLAG"] intValue];
    if (self.isZan == 1) {
         [self.zanBtn setImage:IMG(@"zan2") forState:UIControlStateNormal];
    }else {
         [self.zanBtn setImage:IMG(@"zan1") forState:UIControlStateNormal];
        
    }
  
   
}
- (void)handleZanAction:(id)sender
{
    
    
   
    if (self.isZan == 1) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"您已经点赞～"];
            //                [SVProgressHUD dismissWithDelay:10];
        });
        return;
    }
    
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                             @"id":[self.dict objectForKey:@"TALK_ID"],
                             @"TOKEN":user.TOKEN
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_CIRCLE_37 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showInfoWithStatus:@"点赞成功"];
            //                [SVProgressHUD dismissWithDelay:10];
        });
        [self.zanBtn setImage:IMG(@"zan2") forState:UIControlStateNormal];
        NSInteger num = self.zanBtn.titleLabel.text.integerValue + 1;
        [self.zanBtn setTitle:[NSString stringWithFormat:@"%ld",num] forState:UIControlStateNormal];
        self.isZan = 1;
//        self.zanLabel.text = [NSString stringWithFormat:@"%ld个人点赞",self.zanNum];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
}


#pragma mark  SDPhotoBrowserDelegate

// 返回临时占位图片（即原来的小图）
//- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
//{
//    // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
//    SDCollectionViewDemoCell *cell = (SDCollectionViewDemoCell *)[self collectionView:self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
//
//    return cell.imageView.image;
//
//}


//// 返回高质量图片的url
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
   
    return [NSURL URLWithString:self.photos[index]];
}



-  (void)handleBtnAction:(id)sender
{
    UIButton *btn = sender;
    NSInteger tag  = btn.tag - BTNTAG;
    
    
    SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
    photoBrowser.delegate = self;
    photoBrowser.currentImageIndex = tag;;
    photoBrowser.imageCount = self.photos.count;
    photoBrowser.sourceImagesContainerView = self.imgsView;
    [photoBrowser show];
    
//    // 1. 创建动画配置类
//    YCPhotoBrowserAnimator *browserAnimator = [[YCPhotoBrowserAnimator alloc] initWithPresentedDelegate:self];
//    browserAnimator.presentedDelegate  = self;
//    browserAnimator.indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
//    YCPhotoBrowserController *vc = [YCPhotoBrowserController instanceWithShowImagesURLs:self.photos urlReplacing:nil];
//    vc.indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
//      vc.browserAnimator = browserAnimator;
//
//    [[self viewController] presentViewController:vc animated:YES completion:nil];
}




//#pragma mark - <AnimatorPresentedDelegate>
//// 动画需要实现该协议，将动画的image传给动画类
//- (UIImageView *)imageViewWithIndexPath:(NSIndexPath *)index{
//    UIButton *btn = [self.imgsView viewWithTag:index.length+BTNTAG];
//    UIImageView *imageView = [[UIImageView alloc] initWithImage:btn.currentBackgroundImage];
//    return imageView;
//}


- (void)createImgsWithAry:(NSArray *)imgsAry
{
    [self.imgsView removeAllSubviews];
    float width = (BOUNDWIDTH-60-15-20)/3;
      CWeakSelf;
    if (imgsAry.count > 0) {
      @weakify(self);
        [imgsAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            @strongify(self);
            NSDictionary *imgDict = imgsAry[idx];
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            //        [btn setBackgroundImage:IMG([]) forState:UIControlStateNormal];
            //        [btn sd_setImageWithURL:[NSURL URLWithString:APPEND_URL(BASE_URL, [imgDict objectForKey:@"TPLJ00"])] forState:UIControlStateNormal];
            btn.tag = BTNTAG + idx;
            [btn addTarget:self action:@selector(handleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
//            [btn sd_setBackgroundImageWithURL:[NSURL URLWithString:APPEND_URL(BASE_URL, [imgDict objectForKey:@"TPLJ00"])] forState:UIControlStateNormal];

            [self.photos addObject:APPEND_URL(BASE_URL, [imgDict objectForKey:@"TPLJ00"])];
            
            [self.imgsView addSubview:btn];
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(weakSelf.imgsView.mas_left).offset((width+5)*(idx%3));
                make.top.mas_equalTo(weakSelf.imgsView.mas_top).offset((width+5)*(idx/3));
                make.height.mas_equalTo(width);
                make.width.mas_equalTo(width);
                
            }];
            
            UIImageView *imageView = [UIImageView new];
            [imageView sd_setImageWithURL:[NSURL URLWithString:APPEND_URL(BASE_URL, [imgDict objectForKey:@"TPLJ00"])]];
            [btn addSubview:imageView];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            
            


            if (imgsAry.count - 1 == idx) {
                [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(weakSelf.imgsView).offset(-10);
                }];

                [weakSelf.imgsView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(weakSelf.contentView).offset(-25);
                }];

            }
            
        }];
    }
    
    
}


-(void)createConstraint
{
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(15);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(self.contentView.mas_top).offset(15);
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(60);
        make.right.mas_equalTo(self.contentView.mas_right).offset(-15);
        make.top.mas_equalTo(self.contentView.mas_top).offset(15);
        make.width.mas_equalTo(15);
    }];

    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(60);
        make.right.mas_equalTo(self.contentView.mas_right).offset(-15);
        make.top.mas_equalTo(self.nameLabel.mas_bottom).offset(5);
        make.width.mas_equalTo(11);
    }];

    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(60);
        make.right.mas_equalTo(self.contentView.mas_right).offset(-15);
        make.top.mas_equalTo(self.dateLabel.mas_bottom).offset(10);
    }];

    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(60);
        make.right.mas_equalTo(self.contentView.mas_right).offset(-15);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(5);
    }];
    
    [self.imgsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(60);
        make.right.mas_equalTo(self.contentView.mas_right).offset(-15);
        make.top.mas_equalTo(self.contentLabel.mas_bottom).offset(-20);
    }];
    
    [self.commentBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.contentView.mas_right).offset(-15);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-5);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(40);
    }];
    
    [self.zanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.commentBtn.mas_left).offset(-5);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-5);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(40);
    }];
    
    
    [self.lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView.mas_left).offset(0);
        make.right.mas_equalTo(self.contentView.mas_right).offset(0);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(0);
        make.height.mas_equalTo(0.5);
  
    }];
}

- (UIImageView *)logoImageView
{
    if (!_logoImageView) {
        _logoImageView = [UIImageView new];
        _logoImageView.layer.cornerRadius = 20;
        _logoImageView.layer.masksToBounds = YES;
    }
    return _logoImageView;
}
- (UILabel *)nameLabel
{
    if (!_nameLabel) {
        _nameLabel = [UILabel new];
        _nameLabel.textColor = Common_TextColor;
        _nameLabel.font = FONT_SIZE(13);
    }
    return _nameLabel;
}

- (UILabel *)dateLabel
{
    if (!_dateLabel) {
        _dateLabel = [UILabel new];
        _dateLabel.textColor = Common_TextLowColor;
        _dateLabel.font = FONT_SIZE(11);
    }
    return _dateLabel;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.textColor = Common_TextColor;
        _titleLabel.font = FONT_SIZE(13);
        _titleLabel.numberOfLines = 0;
    }
    return _titleLabel;
}

- (UILabel *)contentLabel
{
    if (!_contentLabel) {
        _contentLabel = [UILabel new];
        _contentLabel.textColor = Common_TextLowColor;
        _contentLabel.font = FONT_SIZE(13);
        _contentLabel.numberOfLines = 0;
    }
    return _contentLabel;
}
- (UIView *)imgsView
{
    if (!_imgsView) {
        _imgsView = [UIView new];
    }
    return _imgsView;
    
}

- (UIButton *)zanBtn
{
    if (!_zanBtn) {
        _zanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_zanBtn setImage:IMG(@"zan1") forState:UIControlStateNormal];
        [_zanBtn setTitle:@"2" forState:UIControlStateNormal];
        [_zanBtn setTitleColor:Common_TextColor forState:UIControlStateNormal];
        _zanBtn.titleLabel.font = FONT_SIZE(10);
        [_zanBtn setTitleEdgeInsets:UIEdgeInsetsMake(0 ,0, 0.0,-10)];//文字距离上边框的距离增加imageView的高度，距离左边框减少imageView的宽度，距离下边框和右边框距离不变
        [_zanBtn setImageEdgeInsets:UIEdgeInsetsMake( 0, 0,0.0, 0)];//
        [_zanBtn addTarget:self action:@selector(handleZanAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _zanBtn;
    
}

- (UIButton *)commentBtn
{
    if (!_commentBtn) {
        _commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_commentBtn setImage:IMG(@"circle2") forState:UIControlStateNormal];
        [_commentBtn setTitle:@"2" forState:UIControlStateNormal];
        [_commentBtn setTitleColor:Common_TextColor forState:UIControlStateNormal];
        _commentBtn.titleLabel.font = FONT_SIZE(10);
        [_commentBtn setTitleEdgeInsets:UIEdgeInsetsMake(0 ,0, 0.0,-10)];//文字距离上边框的距离增加imageView的高度，距离左边框减少imageView的宽度，距离下边框和右边框距离不变
        [_commentBtn setImageEdgeInsets:UIEdgeInsetsMake( 0, 0,0.0, 0)];//
    }
    return _commentBtn;
    
}

- (UILabel *)lineLabel
{
    if (!_lineLabel) {
        _lineLabel = [UILabel new];
        _lineLabel.backgroundColor = Common_SepeColor;
     
    }
    return _lineLabel;
}

@end
